<?php
/**
 * Created by PhpStorm.
 * User: bzg
 * Date: 2019/11/29
 * Time: 15:02
 */

namespace App\Extend\SysExtend\Cache;


use App\Extend\SysExtend\Helper;
use EasySwoole\Component\Singleton;

/**
 * 缓存处理
 * Class Cache
 * @package App\Extend\SysExtend\Cache
 */
class Cache
{
    use Singleton;

    private $driver_obj;

    /**
     * 构造函数
     * Cache constructor.
     */
    private function __construct()
    {
        // 从配置项中读取当前的缓存驱动和配置信息，用来初始化缓存对象
        $config = Helper::config('cache');
        // 注册缓存驱动
        $this->driver_obj = new $config['driver'];
        $this->driver_obj->register($config[$config['driver']]);
    }

    public function getDriver()
    {
        return $this->driver_obj;
    }

    public static function __callStatic($name, $params)
    {
        $obj = self::getInstance();
        // 获取一个驱动连接
        $driver = $obj->getDriver()->getInstance();
        // 数组序列化
        if(!empty($params)) {
            foreach ($params as &$p) {
                if(is_array($p)) {
                    $p = json_encode($p);
                }
            }
        }
        // 执行方法
        $res = $driver->$name(... $params);
        // 回收对象
        $obj->getDriver()->recycle($driver);
        // 数据反序列化
        $json = json_decode($res,true);
        if(!is_array($json)) {
            return $res;
        }
        // 返回数据
        return $json;
    }
}